package cn.wolfcode.trip.app.filter;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

//图片过滤器
public class ImagesFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException{

    }


    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前请求的图片路径
        HttpServletRequest req = (HttpServletRequest)request;
        //getRequestURI当前访问的地址   端口号前的地址
        String imgURI = req.getRequestURI();

        //先查找当前项目的upload中是否存在该文件(绝对路径   /的绝对路径就是webapp)
        String path = request.getServletContext().getRealPath("/");//ServletContext 上下文对象
        File file = new File(path,imgURI); //目标结果

        //取反,文件不存在
        if(!file.exists()){
            //如果不存在,就去公共文件夹中拷贝到当前项目的upload中,才放行
            File srcFile = new File(UploadUtil.COMMON_PATH, imgURI);
            FileUtils.copyFile(srcFile,file);
        }

        //如果存在,直接放行
        chain.doFilter(request,response);
    }

    public void destroy(){

    }

}
